# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from concurrent import futures
import time

import grpc

from protos import helloworld_pb2
from protos import helloworld_pb2_grpc

from models import session, User


_ONE_DAY_IN_SECONDS = 60 * 60 * 24


class Greeting(helloworld_pb2.GreetingServicer):

    def CreateUser(self, request, context):
        print str(request)
        name = request.name
        user = User(name=name)
        session.add(user)
        session.commit()

        return helloworld_pb2.UserResponse(errcode=0, errmsg='ok', user_id=user.id)

    def SayHello(self, request, context):
        id = request.id
        user = session.query(User).filter(User.id == id).one()
        return helloworld_pb2.HelloResponse(message='Hello, {0}'.format(user.name))


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    helloworld_pb2_grpc.add_GreetingServicer_to_server(Greeting(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()
